package com.mego.maq.activitys;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;

import com.mego.maq.R;
import com.mego.maq.utils.CrashHandler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class WelcomeActivity extends Activity {

    private ProgressBar progress;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.welcome);

        progress = (ProgressBar) this.findViewById(R.id.progress);

        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());
        Thread.setDefaultUncaughtExceptionHandler(crashHandler);

        permissonHandle();

    }

    private void startApp() {
        Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
        startActivity(intent);
        WelcomeActivity.this.finish();
    }

//    , Manifest.permission.ACCESS_COARSE_LOCATION
    private void permissonHandle() {
        //安卓6.0权限请求
        if (ContextCompat.checkSelfPermission(WelcomeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(WelcomeActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(WelcomeActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.ACCESS_FINE_LOCATION}, 111);
        } else {
            AppContext.getInstances().setDatabase();    //初始化数据库
            start();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean writeAccepted = false;
        switch (requestCode) {
            case 111:
                writeAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if (writeAccepted) {
                    AppContext.getInstances().setDatabase();    //初始化数据库
                    start();
                } else {
                    moveTaskToBack(false);//应用退到后台
                    System.exit(0);
                }
                break;
        }
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    startApp();
                    break;
            }
        }
    };

    private void start() {
//        progress.setVisibility(View.VISIBLE);

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                Message msg = new Message();
                msg.what = 1;
                handler.sendMessage(msg);

            }
        }.start();
    }

    void deepFile(Context ctxDealFile, String path, boolean needRecopy) {
        try {
            String RUNDIR0 = Environment.getExternalStorageDirectory() + "/";
            String str[] = ctxDealFile.getAssets().list(path);
            if (str.length > 0) {//如果是目录
                File file = new File(RUNDIR0 + path);
                file.mkdirs();
                for (String string : str) {
                    path = path + "/" + string;
                    deepFile(ctxDealFile, path, needRecopy);
                    path = path.substring(0, path.lastIndexOf('/'));
                }
            } else {//如果是文件
                InputStream is = ctxDealFile.getAssets().open(path);
                File outFile = new File(RUNDIR0 + path);
                if (!needRecopy && outFile.exists()) {
                    return;
                }
                FileOutputStream fos = new FileOutputStream(outFile);
                byte[] buffer = new byte[1024];
                int count = 0;
                while (true) {
                    count++;
                    int len = is.read(buffer);
                    if (len == -1) {
                        break;
                    }
                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}